package com.triones.api.service.interlace.impl;

import cn.dev33.satoken.secure.BCrypt;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import com.amazonaws.util.json.Jackson;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.php.OpenCardTransactionType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.IdempotentKeyGenerator;
import com.ruoyi.common.utils.SnCreator;
import com.ruoyi.common.utils.StringUtils;
import com.triones.api.entity.*;
import com.triones.api.entity.interlace.bo.*;
import com.triones.api.entity.interlace.bo.request.*;
import com.triones.api.entity.interlace.dto.*;
import com.triones.api.entity.interlace.vo.*;
import com.triones.api.entity.interlace.vo.response.InfinityCardDetailsResponse;
import com.triones.api.entity.interlace.vo.response.PhysicalCardFeesResponse;
import com.triones.api.entity.interlace.vo.response.PhysicalCardShippingFeesResponse;
import com.triones.api.entity.param.BankCardTxnParams;
import com.triones.api.entity.vo.BankCardTxnVO;
import com.triones.api.entity.vo.CustomEcWalletBillVO;
import com.triones.api.entity.vo.FeeThaliVO;
import com.triones.api.mapper.CountryDictMapper;
import com.triones.api.mapper.FeeThaliMapper;
import com.triones.api.mapper.StateDictMapper;
import com.triones.api.mapper.interlace.*;
import com.triones.api.service.interlace.InterlaceCommunalService;
import com.triones.api.service.interlace.InterlaceFiatService;
import com.triones.api.service.third.InterlaceService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * interlace 法定货币相关接口
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class InterlaceFiatServiceImpl implements InterlaceFiatService {

    @Value("${spring.profiles.active}")
    private String activeProfile;

    private final InterlaceService interlaceService;

    private final InterlaceCommunalService interlaceCommunalService;

    private final InterlaceBudgetMapper interlaceBudgetMapper;

    private final InterlaceMemberMapper interlaceMemberMapper;

    private final InterlaceBalancesMapper interlaceBalancesMapper;

    private final InterlaceCardBinsMapper interlaceCardBinsMapper;

    private final InterlaceInfinityCardMapper interlaceInfinityCardMapper;

    private final InterlaceShipPhysicalCardsMapper interlaceShipPhysicalCardsMapper;

    private final InterlaceKycMapper interlaceKycMapper;

    private final InterlaceCardHolderMapper interlaceCardHolderMapper;

    private final InterlaceBudgetTransactionMapper interlaceBudgetTransactionMapper;

    private final InterlaceCardTransactionMapper interlaceCardTransactionMapper;

    private final InterlaceCardFreezeRecordMapper interlaceCardFreezeRecordMapper;

    private final InterlaceCardApplyMapper interlaceCardApplyMapper;

    private final CountryDictMapper countryDictMapper;

    private final StateDictMapper stateDictMapper;

    private final FeeThaliMapper feeThaliMapper;

    private final InterlaceCardTransactionFeeMapper interlaceCardTransactionFeeMapper;

    private final InterlaceCardBillStatisticsMapper interlaceCardBillStatisticsMapper;

    @Override
    public List<CustomInterlaceBudgetVO> budgetListGroup() {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        return interlaceBudgetMapper.budgetListGroup(loginUser.getUserId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createBudget(InterlaceBudgetBO bo) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        InterlaceMemberVO memberVO = interlaceMemberMapper.selectVoById(loginUser.getUserId());
        if (memberVO == null) {
            throw new ServiceException("用户不存在！");
        }
        return true;
    }

    @Override
    public boolean updateBudgetName(Long id, String name) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        InterlaceBudgetDO budgetDO = interlaceBudgetMapper.selectById(id);
        if (budgetDO == null) {
            throw new SecurityException("预算组不存在！");
        }
        InterlaceBudgetDO interlaceBudgetDO = interlaceBudgetMapper.selectOne(new LambdaQueryWrapper<InterlaceBudgetDO>()
            .eq(InterlaceBudgetDO::getUid, loginUser.getUserId())
            .eq(InterlaceBudgetDO::getNickname, name));
        if (interlaceBudgetDO != null) {
            throw new ServiceException("名称已存在！");
        }
        budgetDO.setNickname(name);
        budgetDO.setUpdateTime(System.currentTimeMillis());
        return interlaceBudgetMapper.updateById(budgetDO) > 0;
    }

    @Override
    public List<InterlaceCardBinsVO> getCardBinList(String type) {
        if (type == null) {
            type = "BudgetCard";
        }
        return interlaceCardBinsMapper.selectVoList(new LambdaQueryWrapper<InterlaceCardBinsDO>()
            .eq(InterlaceCardBinsDO::getEnv, activeProfile)
            .eq(InterlaceCardBinsDO::getStatus, "0")
            .eq(InterlaceCardBinsDO::getDel, "0")
            .eq(InterlaceCardBinsDO::getType, type)
            .orderByAsc(InterlaceCardBinsDO::getCreateTime));
    }

    @Override
    public PhysicalCardFeesResponse getPhysicalCardFees(PhysicalCardFeesRequest request) {
        List<Map> response = interlaceService.physicalCardFees(request);
        if (response != null && response.size() > 0) {
            Map map = response.get(0);
            PhysicalCardFeesResponse feesResponse = new PhysicalCardFeesResponse();
            feesResponse.setCountry(Convert.toStr(map.get("country")));
            List<Map> shippingFees = (List<Map>) map.get("shippingFees");
            if (shippingFees != null && shippingFees.size() > 0) {
                List<PhysicalCardShippingFeesResponse> shippingFeesResponseList = new ArrayList<>();
                for (Map shippingFee : shippingFees) {
                    PhysicalCardShippingFeesResponse shippingFeesResponse = new PhysicalCardShippingFeesResponse();
                    shippingFeesResponse.setFee(Convert.toStr(shippingFee.get("fee")));
                    shippingFeesResponse.setRange(Convert.toList(Integer.class, shippingFee.get("range")));
                    shippingFeesResponseList.add(shippingFeesResponse);
                }
                feesResponse.setShippingFees(shippingFeesResponseList);
            }
            return feesResponse;
        } else {
            throw new ServiceException("没有查询到邮寄到该国家的邮寄费用列表！");
        }
    }

    @Override
    public boolean physicalCardShip(PhysicalCardShipBO bo) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        List<Long> cardIds = bo.getCardIds();
        if (cardIds == null || cardIds.size() <= 0) {
            throw new ServiceException("请选择要处理的卡片！");
        }
        List<InterlaceInfinityCardDO> cardList = new ArrayList<>();
        for (Long cardId : cardIds) {
            InterlaceInfinityCardDO cardDO = interlaceInfinityCardMapper.selectById(cardId);
            if (cardDO == null) {
                throw new ServiceException("卡片不存在！");
            }
            cardList.add(cardDO);
        }

        /** 发起邮寄 */
//        BulkShipPhysicalCardsRequest request = new BulkShipPhysicalCardsRequest();
//        BeanUtil.copyProperties(bo, request);
//        ShippingAddressRequest shippingAddress = new ShippingAddressRequest();
//        BeanUtil.copyProperties(bo, shippingAddress);
//        Boolean shipPhysicalCardsResponse = interlaceService.bulkShipPhysicalCards(request);
//        if (shipPhysicalCardsResponse) {
//
//        }
        for (InterlaceInfinityCardDO cardDO : cardList) {
            InterlaceShipPhysicalCardsDO interlaceShipPhysicalCardsDO = new InterlaceShipPhysicalCardsDO();
            interlaceShipPhysicalCardsDO.setUid(loginUser.getUserId());
            interlaceShipPhysicalCardsDO.setAccountId(cardDO.getAccount());
            interlaceShipPhysicalCardsDO.setCardId(cardDO.getCardId());
            interlaceShipPhysicalCardsDO.setEmail(bo.getEmail());
            interlaceShipPhysicalCardsDO.setPhone(bo.getPhone());
            interlaceShipPhysicalCardsDO.setPhoneCode(bo.getPhoneCode());
            interlaceShipPhysicalCardsDO.setFirstName(bo.getFirstName());
            interlaceShipPhysicalCardsDO.setLastName(bo.getLastName());
            interlaceShipPhysicalCardsDO.setShipAddressLine1(bo.getAddressLine1());
            interlaceShipPhysicalCardsDO.setShipAddressLine2(bo.getAddressLine2());
            interlaceShipPhysicalCardsDO.setShipCity(bo.getCity());
            interlaceShipPhysicalCardsDO.setShipState(bo.getState());
            interlaceShipPhysicalCardsDO.setShipCountry(bo.getCountry());
            interlaceShipPhysicalCardsDO.setPostalCode(bo.getPostalCode());
            interlaceShipPhysicalCardsDO.setCreateTime(System.currentTimeMillis());
            interlaceShipPhysicalCardsDO.setUpdateTime(System.currentTimeMillis());
            interlaceShipPhysicalCardsMapper.insert(interlaceShipPhysicalCardsDO);
            cardDO.setIsShip("1");
            cardDO.setUpdateTime(System.currentTimeMillis());
            interlaceInfinityCardMapper.updateById(cardDO);

        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean openBudgetCard(InterlaceInfinityBudgetCardBO bo) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        if (!("PhysicalCard".equals(bo.getCardMode()) || "VirtualCard".equals(bo.getCardMode()))) {
            throw new ServiceException("请选择正确的卡模式！");
        }
        /** 限制实体卡开通 */
        if ("PhysicalCard".equals(bo.getCardMode())) {
            throw new ServiceException("暂未开通，敬请期待！");
        }
        /** 查询开卡费用 */
        FeeThaliDO openCardFee = feeThaliMapper.selectOne(new LambdaQueryWrapper<FeeThaliDO>()
            .eq(FeeThaliDO::getType, "open_card")
            .eq(FeeThaliDO::getSubType, bo.getCardMode())
            .eq(FeeThaliDO::getStatus, "0")
            .last("limit 1"));
        if (openCardFee == null) {
            throw new ServiceException("暂不支持开卡！");
        }
        /** 查询对应的钱包 */
        InterlaceBalancesDO balances = interlaceBalancesMapper.selectOne(new LambdaQueryWrapper<InterlaceBalancesDO>()
            .eq(InterlaceBalancesDO::getUid, loginUser.getUserId())
            .eq(InterlaceBalancesDO::getWalletType, "Budget")
            .eq(InterlaceBalancesDO::getCurrency, "USD")
            .last("limit 1 FOR UPDATE"));
        if (balances == null) {
            throw new ServiceException("用户未绑定钱包！");
        }
        if (!interlaceCommunalService.checkBalances(balances, Convert.toBigDecimal(openCardFee.getFeeConfig()))) {
            throw new ServiceException("账户USD货币余额不足！", 10010);
        }
        String type = "BudgetCard";
        String useType = "shopping";
        /** 检查卡bin信息 */
        InterlaceCardBinsDO interlaceCardBinsDO = interlaceCardBinsMapper.selectOne(new LambdaQueryWrapper<InterlaceCardBinsDO>()
            .eq(InterlaceCardBinsDO::getBin, bo.getBin())
            .eq(InterlaceCardBinsDO::getStatus, "0")
            .eq(InterlaceCardBinsDO::getType, type));
        if (interlaceCardBinsDO == null) {
            throw new ServiceException("卡bin信息不存在！");
        }
        /** 获取用户kyc信息 */
        InterlaceKycDO interlaceKycDO = interlaceKycMapper.selectOne(new LambdaQueryWrapper<InterlaceKycDO>()
            .eq(InterlaceKycDO::getUid, loginUser.getUserId())
            .eq(InterlaceKycDO::getStatus, "Passed"));
        if (interlaceKycDO == null) {
            throw new ServiceException("没有查询到用户有效的kyc信息！");
        }
        /** 获取预算信息 */
        InterlaceBudgetDO interlaceBudgetDO = interlaceBudgetMapper.selectOne(new LambdaQueryWrapper<InterlaceBudgetDO>()
            .eq(InterlaceBudgetDO::getAccountId, interlaceKycDO.getInterlaceAccountId())
            .eq(InterlaceBudgetDO::getStatus, "Active")
            .eq(InterlaceBudgetDO::getUid, loginUser.getUserId()));
        if (interlaceBudgetDO == null) {
            throw new ServiceException("不具备开预算卡资格！");
        }
        /** 获取持卡人信息 */
        InterlaceCardHolderDO interlaceCardHolderDO = interlaceCardHolderMapper.selectOne(new LambdaQueryWrapper<InterlaceCardHolderDO>()
            .eq(InterlaceCardHolderDO::getUid, loginUser.getUserId())
            .eq(InterlaceCardHolderDO::getStatus, "Active"));
        if (interlaceCardHolderDO == null) {
            throw new ServiceException("没有查询到用户持卡人信息！");
        }
        /** 发起开卡申请 */
        String labelId = IdempotentKeyGenerator.generateIdempotentKey();
        CreateInfinityCardToBudgetRequest request = new CreateInfinityCardToBudgetRequest();
        request.setAccountId(interlaceKycDO.getInterlaceAccountId());
        request.setType(type);
        request.setBin(interlaceCardBinsDO.getBin());
        request.setBatchCount(1);
        request.setLabel(labelId);
        request.setPhoneCode(interlaceKycDO.getPhoneCountryCode());
        request.setPhone(interlaceKycDO.getPhoneNumber());
        request.setUseType(useType);
        request.setCardMode(bo.getCardMode());
        request.setBudgetId(interlaceBudgetDO.getRid());
        request.setCardholderId(interlaceCardHolderDO.getRid());

        /** 保存申请记录 */
        InterlaceCardApplyDO cardApplyDO = new InterlaceCardApplyDO();
        cardApplyDO.setUid(loginUser.getUserId());
        cardApplyDO.setLabelId(labelId);
        cardApplyDO.setCardMode(bo.getCardMode());
        cardApplyDO.setBin(interlaceCardBinsDO.getBin());
        cardApplyDO.setCurrencies(interlaceCardBinsDO.getCurrencies());
        cardApplyDO.setNetwork(interlaceCardBinsDO.getNetwork());
        cardApplyDO.setStatus("Pending");
        cardApplyDO.setCardObjJson(Jackson.toJsonString(request));
        cardApplyDO.setFeeDetail(openCardFee.getFeeConfig());

        /** 发起开卡 2025-11-07修改 */
        /** 发起开卡申请 */
        try {
            Boolean openCardResponse = interlaceService.createInfinityCardToBudget(request);
            cardApplyDO.setApplyResponseMsg(openCardResponse ? "1" : "0");
        } catch (Exception e) {
            cardApplyDO.setApplyResponseMsg(e.getMessage());
        }
        cardApplyDO.setCreateTime(System.currentTimeMillis());
        cardApplyDO.setUpdateTime(System.currentTimeMillis());
        return interlaceCardApplyMapper.insert(cardApplyDO) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean openPrepaidCard(InterlaceInfinityPrepaidCardBO bo) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        String type = "PrepaidCard";
        return true;
    }

    @Override
    public InfinityCardDetailsResponse cardImportantInfo(String password, Long id) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        InterlaceMemberDO interlaceMemberDO = interlaceMemberMapper.selectById(loginUser.getUserId());
        if (interlaceMemberDO == null) {
            throw new ServiceException("用户不存在！");
        }
        if (!BCrypt.checkpw(password, interlaceMemberDO.getPassword())) {
            throw new ServiceException("密码错误");
        }
        InterlaceInfinityCardDO infinityCardDO = interlaceInfinityCardMapper.selectById(id);
        if (infinityCardDO == null) {
            throw new ServiceException("卡不存在！");
        }
        /** 发起获取卡详情 */
        Map mapResponse = interlaceService.infinityCardDetails(infinityCardDO.getCardId());
        if (mapResponse != null) {
            InfinityCardDetailsResponse infinityCardDetailsResponse = new InfinityCardDetailsResponse();
            infinityCardDetailsResponse.setCardNo(Convert.toStr(mapResponse.get("cardNo")));
            infinityCardDetailsResponse.setCvv(Convert.toStr(mapResponse.get("cvv")));
            infinityCardDetailsResponse.setExpYear(Convert.toStr(mapResponse.get("expYear")));
            infinityCardDetailsResponse.setExpMonth(Convert.toStr(mapResponse.get("expMonth")));
            return infinityCardDetailsResponse;
        }
        throw new ServiceException("获取卡详情失败！");
    }

    @Override
    public boolean InfinityCardTransferIn(InfinityCardTransferBO bo) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        if (bo.getCost().compareTo(BigDecimal.ZERO) <= 0) {
            throw new ServiceException("交易金额必须大于0！");
        }
        InterlaceInfinityCardDO infinityCardDO = interlaceInfinityCardMapper.selectById(bo.getId());
        if (infinityCardDO == null) {
            throw new ServiceException("卡不存在！");
        }
        InterlaceBalancesDO balancesDO = interlaceBalancesMapper.selectOne(new LambdaQueryWrapper<InterlaceBalancesDO>()
            .eq(InterlaceBalancesDO::getUid, loginUser.getUserId())
            .eq(InterlaceBalancesDO::getCurrency, "USD")
            .eq(InterlaceBalancesDO::getWalletType, "QuantumAccount")
            .last("FOR UPDATE"));
        if (balancesDO == null) {
            throw new ServiceException("没有查询到可用的钱包！");
        }
        /** 发起交易 */
        String idempotentKey = IdempotentKeyGenerator.generateIdempotentKey();
        InfinityCardTransferRequest request = new InfinityCardTransferRequest();
        request.setCardId(infinityCardDO.getCardId());
        request.setClientTransactionId(idempotentKey);
        request.setCost(bo.getCost());
        Boolean cardTransferInResponse = interlaceService.infinityCardTransferIn(request);
        if (cardTransferInResponse) {
            /** 记录量子账户 */
            InterlaceQuantumTransferDO quantumTransferDO = new InterlaceQuantumTransferDO();
            quantumTransferDO.setUid(loginUser.getUserId());
            quantumTransferDO.setAccountId(infinityCardDO.getAccount());
            quantumTransferDO.setType("transfer_in");
            quantumTransferDO.setAmount(bo.getCost());
            quantumTransferDO.setTransferObj(infinityCardDO.getCardId());
            quantumTransferDO.setClientTransactionId(idempotentKey);
            quantumTransferDO.setStatus("Pending");
            quantumTransferDO.setCreateTime(System.currentTimeMillis());
            quantumTransferDO.setUpdateTime(System.currentTimeMillis());
            interlaceCommunalService.addQuantumTransfer(quantumTransferDO);
        }
        return cardTransferInResponse;
    }

    @Override
    public boolean prepaidCardTransferOut(InfinityCardTransferBO bo) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        if (bo.getCost().compareTo(BigDecimal.ZERO) <= 0) {
            throw new ServiceException("交易金额必须大于0！");
        }
        InterlaceInfinityCardDO infinityCardDO = interlaceInfinityCardMapper.selectById(bo.getId());
        if (infinityCardDO == null) {
            throw new ServiceException("卡不存在！");
        }
        InterlaceBalancesDO balancesDO = interlaceBalancesMapper.selectOne(new LambdaQueryWrapper<InterlaceBalancesDO>()
            .eq(InterlaceBalancesDO::getUid, loginUser.getUserId())
            .eq(InterlaceBalancesDO::getCurrency, "USD")
            .eq(InterlaceBalancesDO::getWalletType, "QuantumAccount")
            .last("FOR UPDATE"));
        if (balancesDO == null) {
            throw new ServiceException("没有查询到可用的钱包！");
        }
        /** 发起交易 */
        String idempotentKey = IdempotentKeyGenerator.generateIdempotentKey();
        InfinityCardTransferRequest request = new InfinityCardTransferRequest();
        request.setCardId(infinityCardDO.getCardId());
        request.setClientTransactionId(idempotentKey);
        request.setCost(bo.getCost());
        Boolean cardTransferOutResponse = interlaceService.infinityCardTransferOut(request);
        if (cardTransferOutResponse) {
            /** 记录量子账户 */
            InterlaceQuantumTransferDO quantumTransferDO = new InterlaceQuantumTransferDO();
            quantumTransferDO.setUid(loginUser.getUserId());
            quantumTransferDO.setAccountId(infinityCardDO.getAccount());
            quantumTransferDO.setType("transfe_out");
            quantumTransferDO.setAmount(bo.getCost());
            quantumTransferDO.setTransferObj(infinityCardDO.getCardId());
            quantumTransferDO.setClientTransactionId(idempotentKey);
            quantumTransferDO.setStatus("Pending");
            quantumTransferDO.setCreateTime(System.currentTimeMillis());
            quantumTransferDO.setUpdateTime(System.currentTimeMillis());
            interlaceCommunalService.addQuantumTransfer(quantumTransferDO);
        }
        return cardTransferOutResponse;
    }

    @Override
    public boolean increaseBudget(BudgetChangeBO bo) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        if (bo.getCost().compareTo(BigDecimal.ZERO) <= 0) {
            throw new ServiceException("交易金额必须大于0！");
        }
        InterlaceBudgetDO interlaceBudgetDO = interlaceBudgetMapper.selectById(bo.getId());
        if (interlaceBudgetDO == null) {
            throw new ServiceException("预算组不存在！");
        }
        String idempotentKey = IdempotentKeyGenerator.generateIdempotentKey();
        BudgetChangeRequest budgetChangeRequest = new BudgetChangeRequest();
        budgetChangeRequest.setBudgetId(interlaceBudgetDO.getRid());
        budgetChangeRequest.setCost(bo.getCost());
        budgetChangeRequest.setClientTransactionId(idempotentKey);
        Boolean budgetBalanceResponse = interlaceService.increaseTheBudgetBalance(budgetChangeRequest);
        if (budgetBalanceResponse) {
            InterlaceBudgetTransactionDO budgetTransactionDO = new InterlaceBudgetTransactionDO();
            budgetTransactionDO.setAccountId(interlaceBudgetDO.getAccountId());
            budgetTransactionDO.setBudgetId(interlaceBudgetDO.getRid());
            budgetTransactionDO.setAmount(bo.getCost());
            budgetTransactionDO.setType("TransferIn");
            budgetTransactionDO.setClientTransactionId(idempotentKey);
            budgetTransactionDO.setStatus("Pending");
            budgetTransactionDO.setTransactionTime(System.currentTimeMillis());
            budgetTransactionDO.setCreateTime(System.currentTimeMillis());
            budgetTransactionDO.setUpdateTime(System.currentTimeMillis());
            interlaceBudgetTransactionMapper.insert(budgetTransactionDO);

            /** 记录量子账户 */
            InterlaceQuantumTransferDO quantumTransferDO = new InterlaceQuantumTransferDO();
            quantumTransferDO.setUid(loginUser.getUserId());
            quantumTransferDO.setAccountId(interlaceBudgetDO.getAccountId());
            quantumTransferDO.setType("budget_increase");
            quantumTransferDO.setAmount(bo.getCost());
            quantumTransferDO.setTransferObj(interlaceBudgetDO.getRid());
            quantumTransferDO.setClientTransactionId(idempotentKey);
            quantumTransferDO.setStatus("Pending");
            quantumTransferDO.setCreateTime(System.currentTimeMillis());
            quantumTransferDO.setUpdateTime(System.currentTimeMillis());
            interlaceCommunalService.addQuantumTransfer(quantumTransferDO);
        }
        return budgetBalanceResponse;
    }

    @Override
    public boolean decreaseBudget(BudgetChangeBO bo) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        if (bo.getCost().compareTo(BigDecimal.ZERO) <= 0) {
            throw new ServiceException("交易金额必须大于0！");
        }
        InterlaceBudgetDO interlaceBudgetDO = interlaceBudgetMapper.selectById(bo.getId());
        if (interlaceBudgetDO == null) {
            throw new ServiceException("预算组不存在！");
        }
        String idempotentKey = IdempotentKeyGenerator.generateIdempotentKey();
        BudgetChangeRequest budgetChangeRequest = new BudgetChangeRequest();
        budgetChangeRequest.setBudgetId(interlaceBudgetDO.getRid());
        budgetChangeRequest.setCost(bo.getCost());
        budgetChangeRequest.setClientTransactionId(idempotentKey);
        Boolean budgetBalanceResponse = interlaceService.decreaseTheBudgetBalance(budgetChangeRequest);
        if (budgetBalanceResponse) {
            InterlaceBudgetTransactionDO budgetTransactionDO = new InterlaceBudgetTransactionDO();
            budgetTransactionDO.setAccountId(interlaceBudgetDO.getAccountId());
            budgetTransactionDO.setBudgetId(interlaceBudgetDO.getRid());
            budgetTransactionDO.setAmount(bo.getCost());
            budgetTransactionDO.setType("TransferOut");
            budgetTransactionDO.setClientTransactionId(idempotentKey);
            budgetTransactionDO.setStatus("Pending");
            budgetTransactionDO.setTransactionTime(System.currentTimeMillis());
            budgetTransactionDO.setCreateTime(System.currentTimeMillis());
            budgetTransactionDO.setUpdateTime(System.currentTimeMillis());
            interlaceBudgetTransactionMapper.insert(budgetTransactionDO);

            /** 记录量子账户 */
            InterlaceQuantumTransferDO quantumTransferDO = new InterlaceQuantumTransferDO();
            quantumTransferDO.setUid(loginUser.getUserId());
            quantumTransferDO.setAccountId(interlaceBudgetDO.getAccountId());
            quantumTransferDO.setType("budget_decrease");
            quantumTransferDO.setAmount(bo.getCost());
            quantumTransferDO.setTransferObj(interlaceBudgetDO.getRid());
            quantumTransferDO.setClientTransactionId(idempotentKey);
            quantumTransferDO.setStatus("Pending");
            quantumTransferDO.setCreateTime(System.currentTimeMillis());
            quantumTransferDO.setUpdateTime(System.currentTimeMillis());
            interlaceCommunalService.addQuantumTransfer(quantumTransferDO);
        }
        return budgetBalanceResponse;
    }

    @Override
    public TableDataInfo<CustomInterlaceBudgetTransactionVO> budgetTransactionPageList(Long id, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        InterlaceBudgetDO interlaceBudgetDO = interlaceBudgetMapper.selectById(id);
        if (interlaceBudgetDO == null) {
            throw new ServiceException("预算组不存在！");
        }
        QueryWrapper<Object> wrapper = Wrappers.query();
        wrapper.eq("tibt.uid", loginUser.getUserId())
            .eq("tibt.budget_id", interlaceBudgetDO.getRid());
        Page<CustomInterlaceBudgetTransactionVO> result = interlaceBudgetTransactionMapper.budgetTransactionPageList(pageQuery.build(), wrapper);
        return TableDataInfo.build(result);
    }

    @Override
    public List<InterlaceInfinityCardVO> budgetCardList(Long id) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        InterlaceBudgetDO interlaceBudgetDO = interlaceBudgetMapper.selectById(id);
        if (interlaceBudgetDO == null) {
            throw new ServiceException("预算组不存在！");
        }
        return interlaceInfinityCardMapper.selectVoList(new LambdaQueryWrapper<InterlaceInfinityCardDO>()
            .eq(InterlaceInfinityCardDO::getType, "BudgetCard")
            .eq(InterlaceInfinityCardDO::getUid, loginUser.getUserId())
            .eq(InterlaceInfinityCardDO::getBudgetId, interlaceBudgetDO.getRid())
            .ne(InterlaceInfinityCardDO::getStatus, "Inactive"));
    }

    @Override
    public List<InterlaceInfinityCardVO> prepaidCardList() {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        return interlaceInfinityCardMapper.selectVoList(new LambdaQueryWrapper<InterlaceInfinityCardDO>()
            .eq(InterlaceInfinityCardDO::getType, "PrepaidCard")
            .eq(InterlaceInfinityCardDO::getUid, loginUser.getUserId()));
    }

    @Override
    public TableDataInfo<CustomInterlaceCardTransactionVO> cardTransactionPageList(PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        QueryWrapper<Object> wrapper = Wrappers.query();
        wrapper.eq("tict.uid", loginUser.getUserId());
        wrapper.ne("tict.type", "Fee_Consumption");
        wrapper.orderByDesc("tict.create_time");
        Page<CustomInterlaceCardTransactionVO> result = interlaceInfinityCardMapper.selectTransactionPageList(pageQuery.build(), wrapper);
        return TableDataInfo.build(result);
    }

    @Override
    public CustomInterlaceCardTransactionVO cardTransactionDetail(Long id) {
        CustomInterlaceCardTransactionVO transactionDetail = interlaceInfinityCardMapper.getTransactionDetail(id);
        if (transactionDetail != null) {
            transactionDetail.setFees(interlaceCardTransactionFeeMapper.selectVoList(new LambdaQueryWrapper<InterlaceCardTransactionFeeDO>()
                .eq(InterlaceCardTransactionFeeDO::getTid, id)));
        }
        return transactionDetail;
    }

    @Override
    public InterlaceShipPhysicalCardsVO getPhysicalCardShipInfo(Long cardId) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        InterlaceInfinityCardDO infinityCardDO = interlaceInfinityCardMapper.selectById(cardId);
        if (infinityCardDO == null) {
            throw new ServiceException("当前卡不存在");
        }
        return interlaceShipPhysicalCardsMapper.selectVoOne(new LambdaQueryWrapper<InterlaceShipPhysicalCardsDO>()
            .eq(InterlaceShipPhysicalCardsDO::getCardId, infinityCardDO.getCardId())
            .eq(InterlaceShipPhysicalCardsDO::getUid, loginUser.getUserId()));
    }

    @Override
    public boolean freezeCard(Long id) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        InterlaceInfinityCardDO infinityCardDO = interlaceInfinityCardMapper.selectById(id);
        if (infinityCardDO == null) {
            throw new ServiceException("当前卡不存在");
        }
        String clientTransactionId = infinityCardDO.getClientTransactionId();
        FreezeInfinityCardRequest request = new FreezeInfinityCardRequest();
        request.setCardId(infinityCardDO.getCardId());
        request.setClientTransactionId(clientTransactionId);
        Boolean freezeResponse = interlaceService.freezeInfinityCard(request);
        if (freezeResponse) {
            /** 保留操作记录 */
            InterlaceCardFreezeRecordDO freezeRecordDO = new InterlaceCardFreezeRecordDO();
            freezeRecordDO.setUid(loginUser.getUserId());
            freezeRecordDO.setClientTransactionId(clientTransactionId);
            freezeRecordDO.setAccountId(infinityCardDO.getAccount());
            freezeRecordDO.setCreateTime(System.currentTimeMillis());
            freezeRecordDO.setType("freeze");
            interlaceCardFreezeRecordMapper.insert(freezeRecordDO);
        }
        return freezeResponse;
    }

    @Override
    public boolean unfreezeCard(Long id) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        InterlaceInfinityCardDO infinityCardDO = interlaceInfinityCardMapper.selectById(id);
        if (infinityCardDO == null) {
            throw new ServiceException("当前卡不存在");
        }
        String clientTransactionId = infinityCardDO.getClientTransactionId();
        FreezeInfinityCardRequest request = new FreezeInfinityCardRequest();
        request.setCardId(infinityCardDO.getCardId());
        request.setClientTransactionId(clientTransactionId);
        Boolean unfreezeResponse = interlaceService.unfreezeInfinityCard(request);
        if (unfreezeResponse) {
            /** 保留操作记录 */
            InterlaceCardFreezeRecordDO freezeRecordDO = new InterlaceCardFreezeRecordDO();
            freezeRecordDO.setUid(loginUser.getUserId());
            freezeRecordDO.setClientTransactionId(clientTransactionId);
            freezeRecordDO.setAccountId(infinityCardDO.getAccount());
            freezeRecordDO.setCreateTime(System.currentTimeMillis());
            freezeRecordDO.setType("unfreeze");
            interlaceCardFreezeRecordMapper.insert(freezeRecordDO);
        }
        return unfreezeResponse;
    }

    @Override
    public void createBudget(String accountId, Long uid) {
        try {
            InterlaceBudgetDO interlaceBudgetDO = interlaceBudgetMapper.selectOne(new LambdaQueryWrapper<InterlaceBudgetDO>()
                .eq(InterlaceBudgetDO::getAccountId, accountId)
                .eq(InterlaceBudgetDO::getUid, uid));
            if (interlaceBudgetDO == null) {
                interlaceBudgetDO = new InterlaceBudgetDO();
                interlaceBudgetDO.setUid(uid);
                interlaceBudgetDO.setAccountId(accountId);
                interlaceBudgetDO.setStatus("Inactive");
                interlaceBudgetDO.setName(IdempotentKeyGenerator.generateIdempotentKey());
                interlaceBudgetDO.setNickname("Master Budget");
                interlaceBudgetDO.setCreateTime(System.currentTimeMillis());
                interlaceBudgetDO.setUpdateTime(System.currentTimeMillis());
                interlaceBudgetMapper.insert(interlaceBudgetDO);
            }
        } catch (Exception e) {
            log.error("创建用户预算组失败，accountId账户{},错误信息{}", accountId, e.getMessage());
        }
    }

    @Override
    public void createCardHolder(String accountId, Long uid) {
        try {
            InterlaceCardHolderDO cardHolderDO = interlaceCardHolderMapper.selectOne(new LambdaQueryWrapper<InterlaceCardHolderDO>()
                .eq(InterlaceCardHolderDO::getAccountId, accountId)
                .eq(InterlaceCardHolderDO::getUid, uid));
            if (cardHolderDO == null) {
                cardHolderDO = new InterlaceCardHolderDO();
                cardHolderDO.setUid(uid);
                cardHolderDO.setAccountId(accountId);
                cardHolderDO.setStatus("Inactive");
                cardHolderDO.setBusinessModel("B2C_GATEWAY");
                cardHolderDO.setCreateTime(System.currentTimeMillis());
                cardHolderDO.setUpdateTime(System.currentTimeMillis());
                interlaceCardHolderMapper.insert(cardHolderDO);
            }
        } catch (Exception e) {
            log.error("创建用户持卡人失败，accountId账户{},错误信息{}", accountId, e.getMessage());
        }
    }

    @Override
    public List<InterlaceInfinityCardVO> cardList() {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        return interlaceInfinityCardMapper.selectVoList(new LambdaQueryWrapper<InterlaceInfinityCardDO>()
            .eq(InterlaceInfinityCardDO::getUid, loginUser.getUserId())
            .ne(InterlaceInfinityCardDO::getStatus, "Inactive"));
    }

    @Override
    public CustomInterlaceInfinityCardVO cardDetail(Long id) {
        InterlaceInfinityCardDO interlaceInfinityCardDO = interlaceInfinityCardMapper.selectById(id);
        try {
            if (interlaceInfinityCardDO != null) {
                /** 发起获取卡详情 */
                GetCardRequest request = new GetCardRequest();
                Map cardResponse = interlaceService.getCard(request, interlaceInfinityCardDO.getCardId());
                if (cardResponse != null) {
                    interlaceInfinityCardDO.setStatus(cardResponse.get("status").toString());
                    interlaceInfinityCardDO.setCardholderId(cardResponse.get("cardholderId").toString());
                    Map statistics = (Map) cardResponse.get("statistics");
                    interlaceInfinityCardDO.setStatisticsConsumption(Convert.toBigDecimal(statistics.get("consumption"), BigDecimal.ZERO));
                    interlaceInfinityCardDO.setStatisticsReversal(Convert.toBigDecimal(statistics.get("reversal"), BigDecimal.ZERO));
                    interlaceInfinityCardDO.setStatisticsReversalFee(Convert.toBigDecimal(statistics.get("reversalFee"), BigDecimal.ZERO));
                    interlaceInfinityCardDO.setStatisticsRefund(Convert.toBigDecimal(statistics.get("refund"), BigDecimal.ZERO));
                    interlaceInfinityCardDO.setStatisticsRefundFee(Convert.toBigDecimal(statistics.get("refundFee"), BigDecimal.ZERO));
                    interlaceInfinityCardDO.setStatisticsNetConsumption(Convert.toBigDecimal(statistics.get("netConsumption"), BigDecimal.ZERO));
                    interlaceInfinityCardDO.setUpdateTime(System.currentTimeMillis());
                    Map velocityControl = (Map) cardResponse.get("velocityControl");
                    if (velocityControl != null) {
                        interlaceInfinityCardDO.setVelocityControlLimit(Convert.toStr(velocityControl.get("limit")));
                        interlaceInfinityCardDO.setVelocityControlType(Convert.toStr(velocityControl.get("type")));
                    }
                    Map balance = (Map) cardResponse.get("balance");
                    if (balance != null) {
                        interlaceInfinityCardDO.setBalanceCurrency(Convert.toStr(balance.get("currency")));
                        interlaceInfinityCardDO.setBalanceAvailable(Convert.toBigDecimal(balance.get("available")));
                        interlaceInfinityCardDO.setBalancePending(Convert.toBigDecimal(balance.get("pending")));
                        interlaceInfinityCardDO.setBalanceFrozen(Convert.toBigDecimal(balance.get("frozen")));
                    }
                    interlaceInfinityCardMapper.updateById(interlaceInfinityCardDO);
                }
            }
        } catch (Exception e) {
            log.error("获取卡详情异常", e);
        }
        CustomInterlaceInfinityCardVO vo = new CustomInterlaceInfinityCardVO();
        BeanUtil.copyProperties(interlaceInfinityCardDO, vo);
        if (vo != null) {
            CountryDictDO billCountry = countryDictMapper.selectOne(new LambdaQueryWrapper<CountryDictDO>()
                .eq(CountryDictDO::getNationalityCountryCode, vo.getBillingAddressCountry()));
            if (billCountry != null) {
                StateDictDO billState = stateDictMapper.selectOne(new LambdaQueryWrapper<StateDictDO>()
                    .eq(StateDictDO::getCountryCode, vo.getBillingAddressCountry())
                    .eq(StateDictDO::getCode, vo.getBillingAddressState()));
                if (billState != null) {
                    vo.setBillingAddressState(billState.getEnName());
                }
                vo.setBillingAddressCountry(billCountry.getEnName());
            }
            if ("PhysicalCard".equals(vo.getCardMode())) {
                InterlaceShipPhysicalCardsVO physicalCardsVO = interlaceShipPhysicalCardsMapper.selectVoOne(new LambdaQueryWrapper<InterlaceShipPhysicalCardsDO>()
                    .eq(InterlaceShipPhysicalCardsDO::getCardId, vo.getCardId())
                    .last("limit 1"));
                if (physicalCardsVO != null) {
                    CountryDictDO shipCountry = countryDictMapper.selectOne(new LambdaQueryWrapper<CountryDictDO>()
                        .eq(CountryDictDO::getNationalityCountryCode, physicalCardsVO.getShipCountry()));
                    if (shipCountry != null) {
                        StateDictDO shipState = stateDictMapper.selectOne(new LambdaQueryWrapper<StateDictDO>()
                            .eq(StateDictDO::getCountryCode, physicalCardsVO.getShipCountry())
                            .eq(StateDictDO::getCode, physicalCardsVO.getShipState()));
                        if (shipState != null) {
                            physicalCardsVO.setShipState(shipState.getEnName());
                        }
                        physicalCardsVO.setShipCountry(shipCountry.getEnName());
                    }
                    vo.setShip(physicalCardsVO);
                }
            }
        }
        return vo;
    }

    @Override
    public PhysicalCardFeesResponse cardProductionFee(String bin) {
        InterlaceCardBinsDO cardBinsDO = interlaceCardBinsMapper.selectOne(new LambdaQueryWrapper<InterlaceCardBinsDO>()
            .eq(InterlaceCardBinsDO::getBin, bin)
            .eq(InterlaceCardBinsDO::getStatus, "0")
            .eq(InterlaceCardBinsDO::getDel, "0")
            .eq(InterlaceCardBinsDO::getEnv, activeProfile)
            .last("limit 1"));
        if (cardBinsDO == null) {
            throw new ServiceException("当前卡BIN信息不存在！");
        }
        PhysicalCardFeesRequest request = new PhysicalCardFeesRequest();
        request.setBin(bin);
        List<Map> response = interlaceService.physicalCardFees(request);
        if (response != null && response.size() > 0) {
            Map map = response.get(0);
            PhysicalCardFeesResponse feesResponse = new PhysicalCardFeesResponse();
            feesResponse.setCountry(Convert.toStr(map.get("country")));
            feesResponse.setCardProductionFee(Convert.toStr(map.get("cardProductionFee")));
            return feesResponse;
        }
        throw new ServiceException("费用获取失败请稍后重试！");
    }

    @Override
    public List<InterlaceCardApplyVO> cardApplyList() {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        return interlaceCardApplyMapper.selectVoList(new LambdaQueryWrapper<InterlaceCardApplyDO>()
            .eq(InterlaceCardApplyDO::getUid, loginUser.getUserId())
            .orderByDesc(InterlaceCardApplyDO::getCreateTime));
    }

    @Override
    public TableDataInfo<CustomInterlaceCardTransactionVO> transactionPageList(BankCardTxnParams params, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        QueryWrapper<Object> wrapper = Wrappers.query();
        wrapper.eq("tict.uid", loginUser.getUserId());
        wrapper.eq(StringUtils.isNotEmpty(params.getCardId()), "tict.card_id", params.getCardId());
        if ("withdrawals".equals(params.getTransactionType())) {
            wrapper.like("tict.remark", "ATM");
        }
        if (params.getDateYearMonth() != null) {
            wrapper.apply("DATE_FORMAT(FROM_UNIXTIME(tict.create_time/1000), '%Y-%m') = {0}", params.getDateYearMonth());
        }
        wrapper.ne("tict.type", "Fee_Consumption");
        wrapper.orderByDesc("tict.create_time");
        Page<CustomInterlaceCardTransactionVO> result = interlaceInfinityCardMapper.selectTransactionPageList(pageQuery.build(), wrapper);
        return TableDataInfo.build(result);
    }

    @Override
    public boolean delivered(Long id) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        InterlaceInfinityCardDO infinityCardDO = interlaceInfinityCardMapper.selectById(id);
        if (infinityCardDO == null) {
            throw new ServiceException("当前卡不存在！");
        }
        InterlaceShipPhysicalCardsDO physicalCardsDO = interlaceShipPhysicalCardsMapper.selectOne(new LambdaQueryWrapper<InterlaceShipPhysicalCardsDO>()
            .eq(InterlaceShipPhysicalCardsDO::getCardId, infinityCardDO.getCardId()));
        if (physicalCardsDO == null) {
            throw new ServiceException("未查询到当前卡的邮寄信息！");
        }
        physicalCardsDO.setStatus("Delivered");
        physicalCardsDO.setDeliveredTime(System.currentTimeMillis());
        physicalCardsDO.setUpdateTime(System.currentTimeMillis());
        return interlaceShipPhysicalCardsMapper.updateById(physicalCardsDO) > 0;
    }

    @Override
    public boolean delCard(String password, Long id) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        InterlaceMemberDO interlaceMemberDO = interlaceMemberMapper.selectById(loginUser.getUserId());
        if (interlaceMemberDO == null) {
            throw new ServiceException("用户不存在！");
        }
        if (!BCrypt.checkpw(password, interlaceMemberDO.getPassword())) {
            throw new ServiceException("密码错误");
        }
        InterlaceInfinityCardDO infinityCardDO = interlaceInfinityCardMapper.selectById(id);
        if (infinityCardDO == null) {
            throw new ServiceException("卡不存在！");
        }
        DeleteCardRequest request = new DeleteCardRequest();
        request.setCardId(infinityCardDO.getCardId());
        if (interlaceService.deleteCard(request)) {
            infinityCardDO.setStatus("Inactive");
            interlaceInfinityCardMapper.updateById(infinityCardDO);
        }
        return true;
    }

    @Override
    public List<InterlaceCardBillStatisticsVO> getBillMonthStatistics(String cardId, String year) {
        return interlaceCardBillStatisticsMapper.selectVoList(new LambdaQueryWrapper<InterlaceCardBillStatisticsDO>()
            .eq(InterlaceCardBillStatisticsDO::getCardId, cardId).eq(InterlaceCardBillStatisticsDO::getBillYear, year));
    }

    @Override
    public boolean velocityControl(VelocityControlBO bo) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        if (!(bo.getType().equals("DAY") ||
            bo.getType().equals("WEEK") ||
            bo.getType().equals("MONTH") ||
            bo.getType().equals("YEAR") ||
            bo.getType().equals("LIFETIME"))) {
            throw new ServiceException("请传入正确的类型！");
        }
        InterlaceInfinityCardDO infinityCardDO = interlaceInfinityCardMapper.selectOne(new LambdaQueryWrapper<InterlaceInfinityCardDO>()
            .eq(InterlaceInfinityCardDO::getCardId, bo.getCardId()));
        if (infinityCardDO == null) {
            throw new ServiceException("卡不存在！");
        }
        VelocityControlRequest request = new VelocityControlRequest();
        request.setCardId(bo.getCardId());
        request.setAccountId(infinityCardDO.getAccount());
        request.setType(bo.getType());
        request.setLimit(bo.getLimit());
        Boolean velocityControlResponse = interlaceService.velocityControl(request);
        if (velocityControlResponse) {
            GetCardRequest cardRequest = new GetCardRequest();
            Map cardResponse = interlaceService.getCard(cardRequest, bo.getCardId());
            if (cardResponse != null) {
                Map velocityControl = (Map) cardResponse.get("velocityControl");
                if (velocityControl != null) {
                    infinityCardDO.setVelocityControlLimit(Convert.toStr(velocityControl.get("limit")));
                    infinityCardDO.setVelocityControlType(Convert.toStr(velocityControl.get("type")));
                }
                Map balance = (Map) cardResponse.get("balance");
                if (balance != null) {
                    infinityCardDO.setBalanceCurrency(Convert.toStr(balance.get("currency")));
                    infinityCardDO.setBalanceAvailable(Convert.toBigDecimal(balance.get("available")));
                    infinityCardDO.setBalancePending(Convert.toBigDecimal(balance.get("pending")));
                    infinityCardDO.setBalanceFrozen(Convert.toBigDecimal(balance.get("frozen")));
                }
                interlaceInfinityCardMapper.updateById(infinityCardDO);
            }
        }
        return velocityControlResponse;
    }

    /**
     * 定时任务-发起创建预算和更新预算组信息（每隔15秒执行）
     */
    @Scheduled(cron = "0/15 * * * * ?")
    public void handleBudget() {
        List<InterlaceBudgetDO> inactiveList = interlaceBudgetMapper.selectList(new LambdaQueryWrapper<InterlaceBudgetDO>()
            .eq(InterlaceBudgetDO::getStatus, "Inactive"));

        List<InterlaceBudgetDO> pendingList = interlaceBudgetMapper.selectList(new LambdaQueryWrapper<InterlaceBudgetDO>()
            .eq(InterlaceBudgetDO::getStatus, "Pending"));

        if (inactiveList != null && inactiveList.size() > 0) {
            for (InterlaceBudgetDO budgetDO : inactiveList) {
                CreateBudgetRequest createBudgetRequest = new CreateBudgetRequest();
                createBudgetRequest.setAccountId(budgetDO.getAccountId());
                createBudgetRequest.setCost(0.00);
                createBudgetRequest.setName(budgetDO.getName());
                String budgetResponse = interlaceService.createBudget(createBudgetRequest);
                if (budgetResponse != null) {
                    budgetDO.setRid(budgetResponse);
                    budgetDO.setStatus("Pending");
                }
            }
            interlaceBudgetMapper.updateBatchById(inactiveList);
        }
        if (pendingList != null && pendingList.size() > 0) {
            for (InterlaceBudgetDO budgetDO : pendingList) {
                ListAllBudgetsRequest request = new ListAllBudgetsRequest();
                request.setAccountId(budgetDO.getAccountId());
                request.setId(budgetDO.getRid());
                Map response = interlaceService.listAllBudgets(request);
                if (response != null) {
                    List<Map> dataList = (List<Map>) response.get("data");
                    if (dataList != null && dataList.size() > 0) {
                        budgetDO.setStatus(Convert.toStr(dataList.get(0).get("status")));
                        budgetDO.setBalanceId(Convert.toStr(dataList.get(0).get("balanceId")));
                        budgetDO.setUpdateTime(System.currentTimeMillis());
                    }
                }
            }
            interlaceBudgetMapper.updateBatchById(pendingList);
        }
    }

    /**
     * 定时任务-发送持卡人申请（每隔10秒执行）
     */
    @Scheduled(cron = "0/10 * * * * ?")
    public void handleHolder() {
        List<InterlaceCardHolderDO> list = interlaceCardHolderMapper.selectList(new LambdaQueryWrapper<InterlaceCardHolderDO>()
            .eq(InterlaceCardHolderDO::getStatus, "Inactive"));
        if (list != null && list.size() > 0) {
            for (InterlaceCardHolderDO interlaceCardHolderDO : list) {
                CreateCardholderRequest request = new CreateCardholderRequest();
                request.setBusinessModel(interlaceCardHolderDO.getBusinessModel());
                String responseId = interlaceService.createCardholder(request, interlaceCardHolderDO.getAccountId());
                interlaceCardHolderDO.setRid(responseId);
                interlaceCardHolderDO.setStatus("Pending");
                interlaceCardHolderDO.setUpdateTime(System.currentTimeMillis());
            }
            interlaceCardHolderMapper.updateBatchById(list);
        }
    }
}
